package com.example.testappwidget.utils;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.RemoteViews;

/**
 * Author: chinadragon
 * Time: 2024/5/7
 */
public class MyAppWidgetProvider extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int appWidgetId : appWidgetIds) {
            // 获取该App Widget的RemoteViews
//            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_appwidget);
//
//            // 获取AppWidget的宽度和高度
//            Point displaySize = getWidgetSize(context, appWidgetManager, remoteViews, appWidgetId);
//            int width = displaySize.x;
//            int height = displaySize.y;

            // 使用宽度和高度...
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    private Point getWidgetSize(Context context, AppWidgetManager appWidgetManager, RemoteViews remoteViews, int appWidgetId) {
        // 获取AppWidget的大小
        AppWidgetProviderInfo appWidgetProviderInfo = appWidgetManager.getAppWidgetInfo(appWidgetId);
        Bundle appWidgetOptions = appWidgetManager.getAppWidgetOptions(appWidgetId);
        int minWidth = appWidgetProviderInfo.minWidth;
        int minHeight = appWidgetProviderInfo.minHeight;
        int width = minWidth;
        int height = minHeight;

        // 如果API版本支持，则从AppWidgetOptions中获取实际大小
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            width = appWidgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
            height = appWidgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
        }

        // 将DP转换为像素
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return new Point(pxFromDp(displayMetrics, width), pxFromDp(displayMetrics, height));
    }

    private int pxFromDp(DisplayMetrics displayMetrics, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, displayMetrics);
    }
}
